package com.cksys.achievement.config;

import com.cksys.achievement.anotation.OpenLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

/**
 * @author tadechen
 * @date 2019/9/23 - 0:39
 */
@Aspect
@Slf4j
@Configuration
public class LogAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 添加切面,这表示对这个注解添加切面
     */
    @Pointcut(value = "@annotation(com.cksys.achievement.anotation.OpenLog)")
    public void openLogAspect() {}

    /**
     * 在openLogAspect切面前,获取注解中的beforeValue写入日志
     * @param pointcut 获取到切点信息
     */
    @Before("openLogAspect()")
    public void before(JoinPoint pointcut) {
        MethodSignature signature = (MethodSignature) pointcut.getSignature();
        OpenLog annotation = signature.getMethod().getAnnotation(OpenLog.class);
        LOGGER.info(annotation.beforeValue());
    }

    /**
     * 在openLogAspect切面正确完成后,获取注解中的beforeValue写入日志
     * @param pointcut 获取到切点信息
     */
    @AfterReturning(pointcut = "openLogAspect()")
    public void after(JoinPoint pointcut) {
        MethodSignature signature = (MethodSignature) pointcut.getSignature();
        OpenLog annotation = signature.getMethod().getAnnotation(OpenLog.class);
        LOGGER.info(annotation.afterReturningValue());
    }

    /**
     * 在openLogAspect切面抛出异常时,将异常写入日志
     * @param error 日常信息
     */
    @AfterThrowing(pointcut = "openLogAspect()", throwing = "error")
    public void throwing(Throwable error) {
        LOGGER.error(error.toString());
    }
}
